"""
WPS文件写入程序

功能：
1. 创建WPS文档
2. 向文档中写入内容
3. 记录操作日志
4. 实时显示WPS文档内容
"""
import logging
import win32com.client
from docx import Document

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='wps_writer.log'
)

def create_wps_file(file_path, content):
    """
    创建WPS文档并写入内容
    
    参数:
        file_path: 文件保存路径
        content: 要写入的内容
    """
    try:
        doc = Document()
        doc.add_paragraph(content)
        doc.save(file_path)
        logging.info(f"成功创建文件: {file_path}")
        
        # 启动WPS并打开文档
        wps = win32com.client.Dispatch("kwps.Application")
        wps.Visible = True
        wps.WindowState = 1  # 1=wdWindowStateMaximize
        wps.Activate()
        import win32gui
        hwnd = win32gui.FindWindow(None, "WPS 文字")
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
        doc = wps.Documents.Open(file_path)
        logging.info(f"已打开WPS显示文档: {file_path}，窗口已最大化并置顶")
    except Exception as e:
        logging.error(f"创建文件失败: {str(e)}")
        if hasattr(e, 'excepinfo') and isinstance(e.excepinfo, tuple):
            logging.error(f"WPS错误详情: {e.excepinfo[2]}")
        raise Exception(f"无法打开WPS文档: {str(e)}")

def auto_create_wps_file():
    """
    自动创建WPS文档并持续随机写入内容，直到用户按键停止
    
    返回:
        创建的文件路径
    """
    import os
    import time
    import random
    import threading
    import msvcrt
    
    file_name = f"auto_wps_{int(time.time())}.docx"
    file_path = os.path.join(os.getcwd(), file_name)
    content = "这是一个自动生成的WPS测试文档\n创建时间: " + time.strftime('%Y-%m-%d %H:%M:%S')
    
    # 创建文档并打开
    try:
        create_wps_file(file_path, content)
    except Exception as e:
        logging.error(f"自动创建文件失败: {str(e)}")
        raise
    
    # 持续随机写入内容
    stop_writing = False
    
    def random_write():
        """持续随机写入内容"""
        logging.info("开始执行random_write函数")
        import pythoncom
        pythoncom.CoInitialize()
        
        # 初始化WPS并保持文档打开状态
        wps = win32com.client.Dispatch("kwps.Application")
        wps.Visible = True
        wps.WindowState = 1  # 1=wdWindowStateMaximize
        wps.Activate()
        import win32gui
        hwnd = win32gui.FindWindow(None, "WPS 文字")
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
        doc = wps.Documents.Open(file_path)
        
        # 获取文档末尾位置
        selection = wps.Selection
        selection.EndKey(6)  # 6=wdStory
        
        while not stop_writing:
            try:
                # 生成随机内容
                random_text = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=10))
                new_content = f"随机内容: {random_text} - {time.strftime('%H:%M:%S')}"
                
                # 逐个字符写入内容
                for char in new_content:
                    selection.TypeText(char)
                    time.sleep(0.05)  # 每个字符间隔50毫秒
                    
                # 换行并添加动画效果
                selection.TypeParagraph()
                for i in range(3):
                    selection.Font.ColorIndex = i+1  # 1=红色, 2=蓝色, 3=绿色
                    selection.Font.Size = 12 + i*2
                    time.sleep(0.1)
                
                # 恢复默认样式
                selection.Font.ColorIndex = 0  # 0=自动(黑色)
                selection.Font.Size = 12
                
                logging.info(f"已写入内容到文件: {file_path}")
                time.sleep(1)
                
            except Exception as e:
                logging.error(f"随机写入失败: {str(e)}")
                if hasattr(e, 'excepinfo') and isinstance(e.excepinfo, tuple):
                    logging.error(f"WPS错误详情: {e.excepinfo[2]}")
                break
            except Exception as e:
                logging.error(f"随机写入失败: {str(e)}")
                if hasattr(e, 'excepinfo') and isinstance(e.excepinfo, tuple):
                    logging.error(f"WPS错误详情: {e.excepinfo[2]}")
                break
    
    def wait_for_key():
        """等待用户按键"""
        nonlocal stop_writing
        print("正在持续写入随机内容，按任意键停止...")
        try:
            # 使用循环检测按键，确保能捕获按键事件
            while not stop_writing:
                if msvcrt.kbhit():
                    msvcrt.getch()
                    stop_writing = True
                    logging.info("用户已按键，停止写入")
                    break
                time.sleep(0.1)
        except Exception as e:
            logging.error(f"按键检测失败: {str(e)}")
            stop_writing = True
    
    # 启动线程
    write_thread = threading.Thread(target=random_write)
    key_thread = threading.Thread(target=wait_for_key)
    
    write_thread.start()
    key_thread.start()
    
    write_thread.join()
    key_thread.join()
    
    return file_path

if __name__ == "__main__":
    """主程序入口"""
    try:
        print("WPS文件写入程序 - 自动创建测试文件")
        file_path = auto_create_wps_file()
        print(f"已自动创建测试文件: {file_path}")
    except Exception as e:
        print(f"发生错误: {str(e)}")